// 加载环境变量
require('dotenv').config();

const express = require('express');
const cors = require('cors');
const path = require('path');

const app = express();
const PORT = process.env.PORT || 30080;

// 中间件
app.use(cors());
app.use(express.json());
app.use(express.static(path.join(__dirname, '../frontend')));

// 基础路由
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, '../frontend/index.html'));
});

// 健康检查端点
app.get('/health', (req, res) => {
    res.json({
        status: 'ok',
        timestamp: new Date().toISOString(),
        uptime: process.uptime(),
        environment: process.env.NODE_ENV || 'development'
    });
});

// API路由
const fortuneRoutes = require('./routes/fortune');
const weatherRoutes = require('./routes/weather');
app.use('/api/fortune', fortuneRoutes);
app.use('/api/weather', weatherRoutes);

// 错误处理中间件
const { errorHandler } = require('./utils/validation');
app.use(errorHandler);

// 404处理
app.use((req, res) => {
    res.status(404).json({
        success: false,
        error: '接口不存在'
    });
});

// 只在非测试环境下启动服务器
if (process.env.NODE_ENV !== 'test') {
    app.listen(PORT, () => {
        console.log(`算命网站服务器运行在 http://localhost:${PORT}`);
    });
}

module.exports = app;